package com.tom.architect02.mnbase.net;

import android.util.Log;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Added by Tom on 2024/05/20.
 */
public class Retrofit {
    // HashMap存储所有的  方法：解析的结果（一个数组）。
    // 懒加载method，第二次请求就走缓存。
    private final Map<Method, ServiceMethod> serviceMethodCache = new ConcurrentHashMap<>();

    public <T> T create(Class<T> service) {
        // 返回的对象，是接口的具体实现。
        return (T) Proxy.newProxyInstance(
                service.getClassLoader(),
                new Class<?>[]{service},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        // 外部调用所有的接口函数，都会进入invoke
                        Log.d("TAG", "invoke " + method.getName());
                        ServiceMethod serviceMethod = loadServiceMethod(method, args);
                        // 用okhttp，请求网络。
                        OkHttpCall okHttpCall = new OkHttpCall(serviceMethod);
                        return okHttpCall;
                    }
                }
        );
    }

    private ServiceMethod loadServiceMethod(Method method, Object[] args) {
        ServiceMethod result = serviceMethodCache.get(method);
        if (result != null) return result;

        // 缓存
        synchronized (serviceMethodCache) {
            if (result == null) {
                result = new ServiceMethod(this, method, args);
                serviceMethodCache.put(method, result);
            }
        }
        return result;
    }


    private String baseUrl; // http://www.kuaidi100.com
    public Retrofit(String baseUrl) {
        this.baseUrl = baseUrl;
    }
    public String getBaseUrl() {
        return baseUrl;
    }

}
